package edu.dublbo.generator.config;

import edu.dublbo.generator.common.utils.JwtUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author habitplus
 * @since 2020-12-27 15:45
 */
@Configuration
public class JwtConfig {
    private static final Logger logger = LoggerFactory.getLogger(JwtConfig.class);

    @Value(value = "${dublbo.web.jwt.expire-time}")
    private String expireTime;

    @Value(value = "${dublbo.web.jwt.token-secret}")
    private String secret;

    @Bean
    public JwtUtils generateJwtVerify() {
        long expireTimeL;
        String tokenSecret;
        if (StringUtils.isEmpty(expireTime) || !NumberUtils.isDigits(expireTime)) {
            // 默认 15 分钟
            expireTimeL = 15 * 60 * 1000;
        } else {
            expireTimeL = Long.parseLong(expireTime);
        }

        if (StringUtils.isEmpty(secret)) {
            tokenSecret = RandomStringUtils.random(32, true, true);
        } else {
            tokenSecret = secret;
        }

        logger.info("Jwt 配置，expireTime = {}, tokenSecret = {}", expireTimeL, tokenSecret);
        return new JwtUtils(expireTimeL, tokenSecret);
    }
}
